package com.jzy.bxb.app.scripts.http.user;

import java.util.Base64;
import java.util.Date;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jzy.bxb.app.manager.RedisManager;
import com.jzy.bxb.core.handler.HandlerEntity;
import com.jzy.bxb.core.handler.HttpHandler;
import com.jzy.bxb.core.util.StringUtil;
import com.jzy.bxb.model.constant.AppConstant;
import com.jzy.bxb.model.constant.RedisKey;
import com.jzy.bxb.model.mongo.dao.ServerInfoDao;
import com.jzy.bxb.model.mongo.dao.UserDao;
import com.jzy.bxb.model.mongo.entity.User;

import redis.clients.jedis.Jedis;

/**
 * 登录 <br>
 * <p>
 * http://127.0.0.1:8680/user/login?userName=18782024395&password=111&type=0<br>
 * http://112.74.36.233:8680/user/login?userName=18782024395&password=111&type=0<br>
 * </p>
 * <li>type 登录类型 0账号密码 1手机登录</li>
 * <li>userName 账号名称</li>
 * <li>password 密码</li>
 * <li>phone 手机号</li>
 * <li>deviceToken 设备唯一标识</li>
 * <li>platform 平台类型 ios android</li>
 * 
 * @author JiangZhiYong
 * @date 2017-06-21 QQ:359135103
 */
@HandlerEntity(path = "/user/login")
public class LoginHandler extends HttpHandler {
	private static final Logger LOGGER = LoggerFactory.getLogger(LoginHandler.class);

	public void run() {
		int type = getInt("type");

		switch (type) {
		case 0:
			loginWithAccount();
			break;
		case 1:
			loginWithPhone();
			break;

		default:
			break;
		}

		getParameter().appendBody("登录成功！");
		response();
	}
	
	/**
	 * 账号登录
	 */
	private void loginWithAccount() {

		String userName = getMessage().getParameter("userName");
		String password = getMessage().getParameter("password");

		if (userName == null || password == null) {
			sendError("请求参数错误");
			return;
		}
		LOGGER.debug("{} 登录客户端", userName);
		User user = UserDao.getByAccount(userName);

		if (user == null) {
			String deviceToken = getString("deviceToken");
			String platform = getString("platform");
			user = new User();
			user.setPassword(password);
			user.setUserName(userName);
			user.setCreateTime(new Date());
			user.setId(ServerInfoDao.incUserNum());
			if (StringUtil.isEmpty(deviceToken)) {
				user.setDeviceToken(userName);
			} else {
				user.setDeviceToken(deviceToken);
			}
			if (StringUtil.isMobile(userName)) {
				user.setPhone(userName);
			}
			if (platform != null) {
				user.setPlatform(platform);
			}
		}

		user.setLoginTime(new Date());
		Jedis client = RedisManager.getInstance().getClient();
		
		if (!user.getPassword().equals(password)) {
			sendError("密码错误");
			return;
		}
		user.setSid(UUID.randomUUID().toString());
		
		client.setex(RedisKey.UserSession.getKey(user.getSid()), AppConstant.SESSION_EXPIRE_TIME,
				String.valueOf(user.getId()));
		client.close();
		UserDao.saveUser(user);

		sendMsg(user);
	}

	

	/**
	 * 账号登录
	 */
	private void loginWithPhone() {

		String userName = getMessage().getParameter("userName");
		String password = getMessage().getParameter("password");

		if (userName == null || password == null) {
			sendError("请求参数错误");
			return;
		}
		LOGGER.debug("{} 登录客户端", userName);
		User user = UserDao.getByAccount(userName);

		if (user == null) {
			String deviceToken = getString("deviceToken");
			user = new User();
			user.setPassword(password);
			user.setUserName(userName);
			user.setCreateTime(new Date());
			user.setId(ServerInfoDao.incUserNum());
			if (StringUtil.isEmpty(deviceToken)) {
				user.setDeviceToken(userName);
			} else {
				user.setDeviceToken(deviceToken);
			}
			if (StringUtil.isMobile(userName)) {
				user.setPhone(userName);
			}
			
		}
		
		String platform = getString("platform");
		if (platform != null) {
			user.setPlatform(platform);
		}

		user.setLoginTime(new Date());
		Jedis client = RedisManager.getInstance().getClient();
		String codeStr = client.get(RedisKey.UserVerificationCode.getKey(userName));
		
		if((codeStr==null||!codeStr.equals(password))
				&&!userName.equals("18782959571"))		//临时测试账号，跳过验证
		{
			sendError("验证码错误");
			return;
		}
		
		user.setSid(UUID.randomUUID().toString());
		
		client.setex(RedisKey.UserSession.getKey(user.getSid()), AppConstant.SESSION_EXPIRE_TIME,
				String.valueOf(user.getId()));
		client.close();
		UserDao.saveUser(user);

		sendMsg(user);
	}

}
